package com.bee2c.osgi.invoke.service.sub;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.caucho.hessian.client.HessianProxyFactory;

public class HessionInvokeUtils {

	private final static Logger log = LoggerFactory.getLogger(HessionInvokeUtils.class);

	public static Map<String, Object> proxyMap = new HashMap<String, Object>();

	@SuppressWarnings("unchecked")
	public static <T> T getHessianProxy(Class<T> adapter, Long timeout, String url) {
		if (StringUtils.isEmpty(url)) {
			log.error("创建HessianAdapter出错。url不能为空");
			return null;
		}
		url = url.trim();
		T proxy = (T) proxyMap.get(url);
		if (proxy != null) {
			return proxy;
		} else {
			try {
				return createHessianAdapter(adapter, timeout, url);
			} catch (Exception e) {
				log.error("创建HessianAdapter异常。", e);
				return null;
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static <T> T createHessianAdapter(Class<T> adapter, Long timeout, String url) throws Exception {
		if (!url.startsWith("http://")) {
			log.error("创建HessianAdapter出错。url必须以http://开始");
			return null;
		}
		if (url.endsWith("/")) {
			log.error("创建HessianAdapter出错。url不能以/结尾");
			return null;
		}
		if (timeout == null) {
			timeout = 30000L;
		}
		HessianProxyFactory factory = new HessianProxyFactory(adapter.getClassLoader());
		factory.setChunkedPost(false);
		factory.setDebug(false);
		// hessian服务属性:是否启用Hessian2协议的应答格式
		factory.setHessian2Reply(true);
		// hessian服务属性:是否启用Hessian2协议的请求格式
		factory.setHessian2Request(true);
		factory.setOverloadEnabled(true);
		factory.setConnectTimeout(20000);
		factory.setReadTimeout(timeout);
		T proxy = (T) factory.create(adapter, url + "/besta/b/h");
		proxyMap.put(url, proxy);
		//
		return proxy;
	}
}
